package com.wyl.clinic.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.wyl.clinic.common.QueryPageParam;
import com.wyl.clinic.common.Result;
import com.wyl.clinic.entity.*;
import com.wyl.clinic.enums.RoleEnum;
import com.wyl.clinic.model.DoctorVo;
import com.wyl.clinic.model.PatientVo;
import com.wyl.clinic.service.*;
import com.wyl.clinic.utils.Md5Util;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 医生表 前端控制器
 * </p>
 *
 * @author wangyulong
 * @since 2024-02-20
 */
@RestController
@RequestMapping("/doctor")
public class DoctorController {

    @Autowired
    private UserService userService;
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private DoctorWorkService doctorWorkService;
    @Autowired
    private RedissonClient redissonClient;

    @PostMapping("/listPage")
    public Result listPage(@RequestBody QueryPageParam query){
        HashMap param = query.getParam();
        String name = (String)param.get("name");
        Page<User> page = new Page(1,2);
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(name)){
            lambdaQueryWrapper.like(User::getName,name);
        }
        lambdaQueryWrapper.eq(User::getRoleId, RoleEnum.DOCTOR.getCode());
        List<DoctorVo> doctorVos = Lists.newArrayList();
        IPage<User> result = userService.page(page,lambdaQueryWrapper);
        List<User> users = result.getRecords();

        if (ObjectUtil.isNotEmpty(users)){
            List<Doctor> doctors = doctorService.listByUserIds(users.stream().map(User::getId).collect(Collectors.toList()));
            Map<Integer, Doctor> doctorMap = doctors.stream().collect(Collectors.toMap(Doctor::getUserId, t -> t, (o1, o2) -> o1));
            users.forEach(user -> {
                DoctorVo doctorVo = new DoctorVo();
                BeanUtils.copyProperties(user, doctorVo);
                Doctor doctor = doctorMap.get(user.getId());
                doctorVo.setId(doctor.getId());
                doctorVo.setUserId(doctor.getUserId());
                doctorVo.setPosition(doctor.getPosition());
                doctorVo.setRemark(doctor.getRemark());
                doctorVo.setImg(doctor.getImg());
                doctorVo.setDepartmentId(doctor.getDepartmentId());
                doctorVos.add(doctorVo);
            });
        }
        return Result.suc(doctorVos,result.getTotal());
    }


    @GetMapping("/list")
    public Result list(@RequestParam(required = false) Integer departmentId){

        DoctorVo doctorVo = new DoctorVo();
        doctorVo.setDepartmentId(departmentId);

        //查科室的医生
        List<Doctor> doctors = doctorService.listByVo(doctorVo);
        return Result.suc(doctors);
    }

    /**
     * 新增
     * @param doctorVo
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody DoctorVo doctorVo){

        User user = userService.lambdaQuery().eq(User::getAccount, doctorVo.getAccount()).one();
        if (ObjectUtil.isNotEmpty(user)){
            return Result.fail("账号存在");
        }
        User userAdd = new User();
        BeanUtils.copyProperties(doctorVo, userAdd);
        userAdd.setPassword(Md5Util.md5Encryp(doctorVo.getPassword()));
        userAdd.setRoleId(RoleEnum.DOCTOR.getCode());
        userService.save(userAdd);

        Doctor doctor = new Doctor();
        BeanUtils.copyProperties(doctorVo, doctor);
        doctor.setUserId(userAdd.getId());
        doctorService.save(doctor);

        return Result.suc();
    }
    /**
     * 更新
     * @param doctorVo
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody DoctorVo doctorVo){
        Doctor doctor = doctorService.getById(doctorVo.getId());
        User user = userService.getById(doctor.getUserId());
        BeanUtils.copyProperties(doctorVo, user);
        user.setPassword(null);
        user.setId(doctor.getUserId());
        userService.updateById(user);

        BeanUtils.copyProperties(doctorVo, doctor);
        doctorService.updateById(doctor);
        return Result.suc();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping("/del")
    public Result del(@RequestParam String id){
        Doctor doctor = doctorService.getById(id);
        if (ObjectUtil.isEmpty(doctor)){
            return Result.suc();
        }
        userService.removeById(doctor.getUserId());
        doctorService.removeById(id);
        return Result.suc();
    }


    /**
     * 查询排班信息
     * @return
     */
    @PostMapping("/workPage")
    public Result work(@RequestBody QueryPageParam query){
        HashMap param = query.getParam();
        String name = (String)param.get("name");


        Integer departmentId = (Integer)param.get("departmentId");;

        Page<DoctorWork> page = new Page(1,2);
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        DoctorVo doctorVo = new DoctorVo();
        doctorVo.setName(name);
        doctorVo.setDepartmentId(departmentId);

        //查科室的医生
        List<Doctor> doctors = doctorService.listByVo(doctorVo);
        if (ObjectUtil.isEmpty(doctors)) return Result.suc();
        List<Integer> dockerIds = doctors.stream().map(Doctor::getId).collect(Collectors.toList());
        Map<Integer, Doctor> dockerMap = doctors.stream().collect(Collectors.toMap(Doctor::getId, t ->t));

        //查医生排班
        LambdaQueryWrapper<DoctorWork> doctorWorkLambdaQueryWrapper = new LambdaQueryWrapper<>();
        doctorWorkLambdaQueryWrapper.in(DoctorWork::getDoctorId, dockerIds);
        doctorWorkLambdaQueryWrapper.ge(DoctorWork::getWorkDate, LocalDate.now());
        doctorWorkLambdaQueryWrapper.orderByDesc(DoctorWork::getId);
        IPage<DoctorWork> doctorWorks = doctorWorkService.page(page,doctorWorkLambdaQueryWrapper);

        List<DoctorWork> result = doctorWorks.getRecords();
        result.forEach(doctorWork -> {
            Doctor doctor = dockerMap.get(doctorWork.getDoctorId());
            RAtomicLong availability = redissonClient.getAtomicLong("doctor:work:availability:"+doctorWork.getId());
            doctorWork.setDoctorName(doctor.getName());
            doctorWork.setResidue(doctorWork.getQuantity() - (int)availability.get());
            doctorWork.setAge(doctor.getAge());
            doctorWork.setPosition(doctor.getPosition());
            doctorWork.setDepartmentName(doctor.getDepartmentName());
        });
        return Result.suc(result, doctorWorks.getTotal());
    }
    /**
     * 查询排班信息
     * @return
     */
    @PostMapping("/workList")
    public Result work(@RequestBody DoctorWork param){

        DoctorVo doctorVo = new DoctorVo();
        doctorVo.setDepartmentId(param.getDepartmentId());

        //查科室的医生
        List<Doctor> doctors = doctorService.listByVo(doctorVo);
        if (ObjectUtil.isEmpty(doctors)) return Result.suc();
        List<Integer> dockerIds = doctors.stream().map(Doctor::getId).collect(Collectors.toList());
        Map<Integer, Doctor> dockerMap = doctors.stream().collect(Collectors.toMap(Doctor::getId, t ->t));

        //查医生排班
        LambdaQueryWrapper<DoctorWork> doctorWorkLambdaQueryWrapper = new LambdaQueryWrapper<>();
        doctorWorkLambdaQueryWrapper.in(DoctorWork::getDoctorId, dockerIds);
        doctorWorkLambdaQueryWrapper.ge(DoctorWork::getWorkDate, LocalDate.now());
        doctorWorkLambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(param.getWorkDate()), DoctorWork::getWorkDate, param.getWorkDate());
        doctorWorkLambdaQueryWrapper.orderByAsc(DoctorWork::getWorkDate);
        List<DoctorWork> result = doctorWorkService.list(doctorWorkLambdaQueryWrapper);

        result.forEach(doctorWork -> {
            Doctor doctor = dockerMap.get(doctorWork.getDoctorId());
            RAtomicLong availability = redissonClient.getAtomicLong("doctor:work:availability:"+doctorWork.getId());
            doctorWork.setDoctorName(doctor.getName());
            doctorWork.setResidue((int)availability.get());
            doctorWork.setAge(doctor.getAge());
            doctorWork.setPosition(doctor.getPosition());
            doctorWork.setDepartmentName(doctor.getDepartmentName());
        });
        return Result.suc(result);
    }

    /**
     * 查询历史排班信息
     * @return
     */
    @GetMapping("/workHistory")
    public Result workHistory(@RequestParam Integer doctorId){

        LambdaQueryWrapper<DoctorWork> doctorWorkLambdaQueryWrapper = new LambdaQueryWrapper<>();
        doctorWorkLambdaQueryWrapper.in(DoctorWork::getDoctorId, doctorId);
        doctorWorkLambdaQueryWrapper.lt(DoctorWork::getWorkDate, LocalDate.now());
        doctorWorkLambdaQueryWrapper.orderByDesc(DoctorWork::getDoctorId).last("limit 100");

        List<DoctorWork> result = doctorWorkService.list(doctorWorkLambdaQueryWrapper);
        return Result.suc(result);
    }

    /**
     * @return
     */
    @PostMapping("/addWork")
    @Transactional
    public Result addWork(@RequestBody DoctorWork doctorWork){
        doctorWorkService.save(doctorWork);
        RAtomicLong availability = redissonClient.getAtomicLong("doctor:work:availability:"+doctorWork.getId());
        availability.set(doctorWork.getQuantity());
        return Result.suc();
    }
    /**
     * @return
     */
    @GetMapping("/delWork")
    public Result delWork(@RequestParam String id){
        DoctorWork doctorWork = doctorWorkService.getById(id);
        RAtomicLong availability = redissonClient.getAtomicLong("doctor:work:availability:"+doctorWork.getId());
        if (doctorWork.getQuantity().longValue() != availability.get()){
            return Result.fail("当前排班已有人挂号，无法删除！");
        }
        doctorWorkService.removeById(id);
        availability.delete();
        return Result.suc();
    }
}
